// 云函数入口文件
const cloud = require('wx-server-sdk')
const request = require('request')
cloud.init()

async function getUserCardInfo(token, postData) {
  let url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" + token;
  //新建promise对象，发起http统一下单请求
  return new Promise((resolve, reject) => {
    try {
      request.post({
        url: url,
        method: "POST",
        json: true,
        headers: {
          "content-type": "application/json",
        },
        body: postData
      },
        function (error, response, body) {
          if (!error && response.statusCode == 200) {
            return resolve(body)
          } else {
            return reject(error)
          }
        })
    } catch (e) {
      return reject(e)
    }
  })
}

const db = cloud.database();

// ---------------------------------------------
// 函数说明：在小程序端自行绑定会员卡号的验证函数
// 返回格式: {result:success/fail, error:'错误说明',more:''}

exports.main = async (event, context) => {

  template_cardid ='p1Jdc1E9hvyb__Rw0xTd877hRWu8'
  cardid = event.cardid
  userid = event.userid
  openid = event.openid

  // ********************【查询数据库】********************
  let list = await db.collection('users').where({ cardid: cardid}).get()
  //------------- 错误检测-err01：数据库访问是否正常
  if (list.errMsg != 'collection.get:ok'){
    return { result: 'fail', error: 'err01:网络错误',more:'读取user数据库错误'}
  }
  let userlist = list.data //记录查询结果 [array]
  //------------- 错误检测-err02：会员卡号是否首次注册
  if (userlist.length !=0){
    return { result: 'fail', error: 'err02:该会员卡号已经绑定过', more: userlist }
  }
  // ********************【获取公众号token】********************
  let tokenPromise = await cloud.callFunction({name: 'getPublicAccessToken'})
  //------------- 错误检测-err03：获取公众号token的云函数是否正确执行
  if (tokenPromise.errMsg != 'callFunction:ok') {
    return { result: 'fail', error: 'err03:网络错误', more: '云函数getPublicAccessToken运行错误' }
  }
  //------------- 错误检测-err04：获取公众号token的云函数是否正确执行
  let token = tokenPromise.result
  if (token == '') {
    return { result: 'fail', error: 'err04:网络错误', more: '云函数getPublicAccessToken返回为空' }
  }
  // ********************【调用腾讯API接口查询用户卡片信息】********************
  let url = "https://api.weixin.qq.com/card/membercard/userinfo/get?access_token=" + token;
  let postData = { card_id: template_cardid, code: cardid}
  let userCardInfoRequest = await postRequest(url, postData)
 //------------- 错误检测-err05: 调用腾讯API接口验证数据信息
  if (userCardInfoRequest ===false){
    return { result: 'fail', error: 'err05:网络错误', more: 'API调用失败' }
  }
  let cardInfo = userCardInfoRequest
  //------------- 错误检测-err06: 卡片信息是否有误
  if (cardInfo.errcode !== 0) {
    return { result: 'fail', error: 'err06:卡片信息错误', more: cardInfo }
  }
  //------------- 错误检测-err07: 用户是否激活卡片
  if (cardInfo.has_active !== true) {
    return { result: 'fail', error: 'err07:会员卡未激活', more: cardInfo }
  }
  //------------- 错误检测-err08: 用户卡片状态是否正常
  if (cardInfo.user_card_status !== "NORMAL") {
    return { result: 'fail', error: 'err08:会员卡状态异常', more: cardInfo }
  }
  // ********************【将用户的卡号和公众号openid记录至数据库】********************
  let user = await db.collection('users').where({ openid: openid, userid: userid}).get()
  //------------- 错误检测-err09: 查询用户信息云函数执行错误
  if (user.errMsg !== "collection.get:ok") {
    return { result: 'fail', error: 'err09:查询用户信息云函数执行错误', more: user }
  }
  //------------- 错误检测-err10: 用户信息有误
  if (user.data.length !== 1) {
    return { result: 'fail', error: 'err10:您的用户信息有误', more: user }
  }
  let doc_id = user.data[0]._id
  let writeInfo = await db.collection('users').doc(doc_id)
  .update({ data: { cardid: cardInfo.membership_number, openid2: cardInfo.openid } })
  //------------- 错误检测-err11: 云函数update运行是否正常
  if (writeInfo.errMsg !== "document.update:ok") {
    return { result: 'fail', error: 'err11:云函数update执行发生错误', more: writeInfo }
  }
  //------------- 错误检测-err12: 写入数据是否正常
  if (writeInfo.stats.updated !== 1) {
    return { result: 'fail', error: 'err12:会员信息写入错误', more: writeInfo }
  }
  // ********************【运行至此说明所有操作无误】********************
  return { result: 'success', error: '', more: '' }
}

async function postRequest(url, postData) {
  //新建promise对象，发起http统一下单请求
  return new Promise((resolve, reject) => {
    try {
      request.post({
        url: url,
        method: "POST",
        json: true,
        headers: {
          "content-type": "application/json",
        },
        body: postData
      },
        function (error, response, body) {
          if (!error && response.statusCode == 200) {
            return resolve(body)
          } else {
            //return reject(error)
            return false
          }
        })
    } catch (e) {
      //return reject(e)
      return false
    }
  })
}